<template>
  <el-dialog
    v-model="visible"
    title="评论管理"
    width="60%"
    :before-close="handleClose"
  >
    <div class="comments-section">
      <el-table
        :data="commentList"
        style="width: 100%"
        v-loading="commentsLoading"
      >
        <el-table-column prop="comment_id" label="评论ID" width="80" />
        <el-table-column prop="author" label="评论者" width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar 
                :size="25" 
                :src="scope.row.author?.avatar"
              >
                {{ scope.row.author?.name?.charAt(0) }}
              </el-avatar>
              <span class="author-name">{{ scope.row.author?.name || '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评论内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="created_at" label="评论时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDeleteComment(scope.row)"
            >
              删除评论
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="commentPagination.page"
          v-model:page-size="commentPagination.limit"
          :page-sizes="[10, 20, 50]"
          :total="commentPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Comment, Publish } from '@/api/modules/publish'
import { getCommentList, deleteComment } from '@/api/modules/publish'

const props = defineProps<{
  modelValue: boolean
  publishData: Publish | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = ref(false)

// 评论列表
const commentList = ref<Comment[]>([])
const commentsLoading = ref(false)

// 评论分页信息
const commentPagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 获取评论列表
const fetchComments = async (publishId: number) => {
  commentsLoading.value = true
  try {
    const response = await getCommentList({
      publish_id: publishId,
      page: commentPagination.value.page,
      limit: commentPagination.value.limit
    })
    
    commentList.value = response.data?.list || []
    if (response.data?.pagination) {
      commentPagination.value.total = response.data.pagination.total || 0
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
  } finally {
    commentsLoading.value = false
  }
}

// 监听弹窗显示状态和发布数据变化
watch([() => props.modelValue, () => props.publishData], async ([newVisible, newPublishData]) => {
  visible.value = newVisible
  if (newVisible && newPublishData && newPublishData.publish_id) {
    commentPagination.value.page = 1
    await fetchComments(newPublishData.publish_id)
  }
}, { immediate: true })

// 处理弹窗关闭
const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  commentPagination.value.limit = val
  commentPagination.value.page = 1
  if (props.publishData?.publish_id) {
    fetchComments(props.publishData.publish_id)
  }
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  commentPagination.value.page = val
  if (props.publishData?.publish_id) {
    fetchComments(props.publishData.publish_id)
  }
}

// 处理删除评论
const handleDeleteComment = async (comment: Comment) => {
  ElMessageBox.confirm(
    `确定要删除这条评论吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    if (!comment.comment_id) return
    
    try {
      await deleteComment({ comment_id: comment.comment_id })
      ElMessage.success('评论删除成功')
      
      // 重新获取评论列表
      if (props.publishData?.publish_id) {
        await fetchComments(props.publishData.publish_id)
      }
    } catch (error) {
      console.error('删除评论失败:', error)
    }
  })
  .catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 14px;
}
</style>